/*
 * @(#)SwitchBackCameraAction.java 0.5 08/12/04
 *
 * Copyright 2008 100town.com. All rights reserved.
 * Use is subject to license terms.
 */
package org.collada.util.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import org.collada._2005._11.colladaschema.Camera;
import org.collada.model.Action;
import org.collada.model.ControlKey;
import org.collada.model.ModifierKey;
import org.collada.util.model.RendableModel;

public class SwitchBackCameraAction extends Action{
	public RendableModel rendableModel;
	public static int defaultKey = KeyEvent.VK_C;
	public static String defaultActionId = "SwitchBackCamera";
	public static List<ModifierKey> ModifierKeys = new ArrayList<ModifierKey>();
	static {
		ModifierKeys.add(ModifierKey.ALT_DOWN_MASK);
	}
	public SwitchBackCameraAction(RendableModel m){
		rendableModel = m;
		ControlKey defaultControl = new ControlKey();
		defaultControl.setKey(defaultKey);
		for(ModifierKey modifierKey: ModifierKeys){
			defaultControl.getModifierKeys().add(modifierKey);
		}
		setControlKey(defaultControl);
		setActionID(defaultActionId);
		getActionListeners().clear();
		getActionListeners().add(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				switchBackCamera();
			}
		});
	}
	public void switchBackCamera(){
		if(rendableModel!=null){
			List<Camera> cameras = rendableModel.getCameras();
			if(cameras!=null && cameras.size()>0){
				String currentCamera = rendableModel.getModel().getActiveCamera();
				if(currentCamera==null){ //Set the first one as current camera
					rendableModel.getModel().setActiveCamera(cameras.get(0).getId());
					rendableModel.setCurrentCamera(cameras.get(0));
					return;
				}else{
					int size = cameras.size();
					for(int i=size-1; i>=0; i--){
						Camera c = cameras.get(i);
						if(currentCamera.equals(c.getId())){
							if(i>0){
								rendableModel.getModel().setActiveCamera(cameras.get(i-1).getId());
								rendableModel.setCurrentCamera(cameras.get(i-1));
							}else{
								rendableModel.getModel().setActiveCamera(cameras.get(size-1).getId());
								rendableModel.setCurrentCamera(cameras.get(size-1));
							}
							return;
						}
					}
					System.out.println("Should never come here!");
					rendableModel.getModel().setActiveCamera(cameras.get(0).getId());
					rendableModel.setCurrentCamera(cameras.get(0));
				}
			}
		}
	}
}